<?php

class itemsActions extends sfActions {

    public function executeIndex(sfWebRequest $request){
        
    }

    public function executeUpdate_file(sfWebRequest $request){
        /* subir archivo a carpeta temporal */
        $csv = $_FILES["csv"]["tmp_name"];

        if ($_FILES["csv"]["type"] == "text/comma-separated-values" || $_FILES["csv"]["type"] == "text/csv"
         || $_FILES["csv"]["type"] == "application/csv" || $_FILES["csv"]["type"] == "application/excel"
         || $_FILES["csv"]["type"] == "application/vnd.ms-excel" || $_FILES["csv"]["type"] == "application/vnd.msexcel"
         || $_FILES["csv"]["type"] == "text/anytext"){
            if ($_FILES["csv"]["error"] > 0){
                $this->getUser()->setFlash('msg',"Error: " . $_FILES["csv"]["error"]);
                $this->redirect('@items');
            }
        }else{
            $this->getUser()->setFlash('msg',"Archivo inválido");
            $this->redirect('@items');
        }
        /* eliminar registros enla bd */
        RelatedItemPeer::doDeleteAll();

        /* insertar registros en bd */
        $handle = fopen($csv, "r");

        if($handle){
            $array = explode("\n", fread($handle, filesize($csv)));
        }
        $total_array = count($array);

        $inserts = "";
        $i = 0;
        while($i<$total_array){
            if($i>=1){/* para que no registre las cabeceras */
                $data = $this->csv_string_to_array($array[$i]);

                if($data[0]!=""){
                    if($inserts==""){
                        $inserts .= "(null,".addslashes(utf8_encode($data[0])).",'".addslashes(utf8_encode($data[1]))."',".sprintf('%06d', addslashes(utf8_encode($data[2]))).",'".addslashes(utf8_encode($data[3]))."',".addslashes(utf8_encode($data[4])).")";
                    }else{
                        $inserts .= ",(null,".addslashes(utf8_encode($data[0])).",'".addslashes(utf8_encode($data[1]))."',".sprintf('%06d', addslashes(utf8_encode($data[2]))).",'".addslashes(utf8_encode($data[3]))."',".addslashes(utf8_encode($data[4])).")";
                    }
                }

                if($i%5000==0 || $i==($total_array-1)){
                    //cada 5000 registros y al final registrar los datos
                    $con = Propel::getConnection();
                    $query = "
                        INSERT INTO %s VALUES ".$inserts.";
                    ";

                    $query = sprintf($query,
                        RelatedItemPeer::TABLE_NAME
                    );

                    $stmt = $con->prepare($query);
                    $stmt->execute();

                    //reinicializa el string de INSERT VALUES
                    $inserts = "";
                }
            }
            $i++;
        }

        $this->getUser()->setFlash('msg','Registros actualizados satisfactoriamente');
        $this->redirect('@items');
    }

    private function csv_string_to_array($str){
        $expr="/,(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))/";
        $results=preg_split($expr,trim($str));
        return preg_replace("/^\"(.*)\"$/","$1",$results);
    }

}